package com.google.code.etrclient;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

public class ETRPreferencesActivity extends PreferenceActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    final EditTextPreference usernamePreference = (EditTextPreference)findPreference("username");
    final EditTextPreference passwordPreference = (EditTextPreference)findPreference("password");
    final ListPreference languagePreference = (ListPreference)findPreference("language");
    usernamePreference.setSummary(usernamePreference.getText());
    passwordPreference.setSummary(buildAsteriskString(passwordPreference.getText()));
    languagePreference.setSummary(languagePreference.getEntry());
    
    usernamePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
      @Override
      public boolean onPreferenceChange(Preference preference, Object newValue) {
        usernamePreference.setSummary(newValue.toString());
        return true;
      }
    });
    passwordPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
      @Override
      public boolean onPreferenceChange(Preference preference, Object newValue) {
        passwordPreference.setSummary(buildAsteriskString(newValue.toString()));
        return true;
      }
    });
    languagePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
      @Override
      public boolean onPreferenceChange(Preference preference, Object newValue) {
        if (newValue.equals(languagePreference.getEntryValues()[0])) {
          languagePreference.setSummary(languagePreference.getEntries()[0]);
        } else if (newValue.equals(languagePreference.getEntryValues()[1])) {
          languagePreference.setSummary(languagePreference.getEntries()[1]);
        }
        return true;
      }
    });
    
  }
  
  /**
   * Generate a string of asterisks which can be displayed in fields where automatic asterisk generation for passwords is not supported.
   * 
   * @param from The string from which the length of the result is calculated.
   * @return String of asterisks with the length of the input string.
   */
  private String buildAsteriskString(String from) {
    String res = "";
    for (int i = 0; i < from.length(); i++) {
      res += "*";
    }
    return res;
  }
  
}
